<template>
  <div class="shop-edit">
    <el-row :gutter="10">
      <el-col :span="5">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>店铺LOGO</span>
          </div>
          <div class="avtar-wrap">
            <div class="avtar-item">
              <el-upload
                class="avatar-uploader"
                action=""
                accept=".png,.jpg,.jpeg"
                :show-file-list="false"
                ref='cvue-upload'
                :headers="accessToken"
                :on-preview="handlePictureCardPreview"
                :multiple="false"
                :http-request="uploadFile"
                :auto-upload="true"
                :file-list="fileList"
                :on-remove="handleRemove">
                <ul class="list-upload-image" v-if="logoFile">
                  <li><img :src="logoFile" class="image-item"></li>
                </ul>    
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <div slot="tip" class="el-upload__tip">支持png/jpg，建议尺寸200*200px，大小不超过2M</div>
              </el-upload>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="19">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>基础信息</span>
          </div>
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="120px"
            class="demo-ruleForm">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="店铺名称" prop="storeName">
                  <el-input v-model.trim="ruleForm.storeName" :disabled="disabled"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="联系电话" prop="telephone">
                  <el-input v-model="ruleForm.telephone" :disabled="disabled"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="场馆限定容量" prop="maxCapacity">
                  <el-input v-model.trim="ruleForm.maxCapacity" :disabled="disabled">
                    <template slot="append">人</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="场馆面积" prop="siteArea">
                  <el-input v-model.trim="ruleForm.siteArea" :disabled="disabled">
                    <template slot="append">㎡</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="20">
                <el-form-item label="地址" prop="address" class="fix-address">
                  <el-row>
                    <el-col :span="8">
                      <el-form-item label="省份" prop="province" label-width="60px">
                        <el-select v-model="ruleForm.province" placeholder="请选择" style="width:100%" clearable @change="getCity">
                          <el-option
                            v-for="item in provinceArr"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="市县" prop="city" label-width="60px">
                        <el-select v-model="ruleForm.city" placeholder="请选择" style="width:100%" clearable>
                          <el-option
                            v-for="item in cityArr"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="" prop="address" label-width="40px">
                        <el-input v-model.trim="ruleForm.address" :disabled="disabled">
                          <el-button slot="append" @click="handlePosition">定位</el-button>
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="20">
                <el-form-item label="地图" prop="sex">
                  <div id="addressMap"></div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="场馆照片" prop="imageFiles">
                  <el-upload
                    class="avatar-uploader"
                    action=""
                    :show-file-list="false"
                    ref='cvue-upload1'
                    :headers="accessToken"
                    :on-preview="handlePictureCardPreview"
                    :multiple="false"
                    :limit="10"
                    accept=".png,.jpg,.jpeg"
                    :http-request="uploadFile1"
                    :auto-upload="true"
                    :file-list="fileList1"
                    :on-remove="handleRemove">
                    <ul v-if="imageFiles.length >= 0" class="list-upload-image fix-upload">
                      <li><i class="el-icon-plus avatar-uploader-icon"></i></li>
                      <li v-for="(item,index) in imageFiles" :key="index">
                        <img :src="item" class="image-item">
                        <i class="el-icon-close icon-close" @click.prevent.stop="deleteImage(index)"></i>
                      </li>
                    </ul>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="14">
                <el-form-item label="场馆介绍" prop="introduce">
                  <el-input v-model.trim="ruleForm.introduce" :disabled="disabled" type="textarea" :rows="14"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
    <div class="edit-footer">
      <el-button @click="confirmDialog" type="primary">保存</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </div>
</template>

<script>
/* eslint-disable */
import {mapGetters} from 'vuex'
import cvueTable from '@/components/cvue-table'
import { validPhone, validIp } from '@/util/validator.js'
import { baseUrl } from '@/config/config'
import BMF from 'browser-md5-file'
import { lazyAMapApiLoaderInstance } from 'vue-amap'
const bmf = new BMF()
var validInt = (rule, value, callback) => {
  const reg = /^[1-9]\d*$/
  if (!reg.test(value) && value) {
    callback(new Error('请输入正整数'))
  } else {
    callback()
  }
}
export default {
  name: 'shop-edit',
  components: {
    cvueTable
  },
  data () {
    return {
      src: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
      ruleForm: {
        "address": "",
        "city": 350100,
        "county": 0,
        "enabled": 0,
        "imageFileIds": [],
        "introduce": "",
        "logoFileId": "",
        "maxCapacity": "",
        "province": 350000,
        "storeName": "",
        "telephone": ""
      },
      rules: {
        storeName: [
          { required: true, message: '请输入店铺名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        telephone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          // { validator: validPhone, trigger: 'blur' }
        ],
        maxCapacity: [
          { required: true, message: '请输入场馆限定容量', trigger: 'blur' },
          { validator: validInt, trigger: 'blur' }
        ],
        siteArea: [
          { required: true, message: '请输入场馆面积', trigger: 'blur' },
          { validator: validInt, trigger: 'blur' }
        ],
        province: [
          { required: true, message: '请选择省份', trigger: 'blur' }
        ],
        city: [
          { required: true, message: '请选择市县', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请选择输入详细地址', trigger: 'blur' }
        ]
      },
      disabled: false,
      provinceArr: [],
      cityArr: [],
      aMap: null,
      map: {
        animateEnable: false,
        resizeEnable: true,
        // center: [119.296389, 26.074268],
        zoom: 11,
        expandZoomRange: true,
        zooms: [3, 21]
      },
      markPosition: [],
      fileList: [],
      fileList1: [],
      logoFileId: '',
      logoFile: '',
      imageFiles: [],
      imageFileIds: [],
      shopId: ''
    }
  },
  beforeRouteLeave (to, from, next) {
    // if (this.$route.query.action == 'edit') {
    //   this.$confirm('确定要离开编辑页面吗?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     next()
    //   }).catch(() => {
    //     location.reload()
    //   })
    // } else {
    //   next()
    // }
    next()
  },
  computed: {
    ...mapGetters(['token', 'userInfo', 'tagCurrent']),
    accessToken () {
      var accessToken = {
        'Authorization': this.token
      }
      return accessToken
    }
  },
  mounted () {
    this.getAreaList(0)
    this.getAreaList(this.ruleForm.province)
  },
  activated () {
    lazyAMapApiLoaderInstance.load().then(() => {
      this.aMap = new AMap.Map('addressMap', this.map)
      this.aMap.on('click', this.getPosition)
      this.locationCity()
      if (this.$route.query.action == 'edit') {
        this.getStoreDetail()
      }
    })
  },
  methods: {
    locationCity() {
      let self = this
      AMap.plugin('AMap.CitySearch', function() {
        var citySearch = new AMap.CitySearch()
        citySearch.getLocalCity(function (status, result) {
          if (status === 'complete' && result.info === 'OK') {
            self.city = result.city
            self.aMap.setCity(result.city)
          }
        })
      })
    },
    getPosition (e) {
      this.markPosition = [e.lnglat.getLng(),e.lnglat.getLat()]
      // this.getAdress(this.markPosition)
      this.addMarker(this.markPosition)
    },
    addMarker (position) {
      if (this.marker) {
        this.aMap.remove(this.marker)
      }
      this.marker = new AMap.Marker({
        position: position,
        // anchor: "bottom-center"
      })
      this.aMap.add(this.marker)
      // this.aMap.setCenter(position)
      this.aMap.setFitView()
    },
    handlePosition () {
      var self = this
      AMap.plugin(['AMap.PlaceSearch'], function () {
        var placeSearch = new AMap.PlaceSearch({
          city: self.city,
          pageSize: 1, // 单页显示结果条数
          pageIndex: 1, // 页码
          citylimit: true,  //是否强制限制在设置的城市内搜索
          // map: self.aMap, // 展现结果的地图实例
          autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
          children: 0, //不展示子节点数据
          extensions: 'base' //返回基本地址信息
        })
        placeSearch.search(self.ruleForm.address, function(status, result){
          if (status === 'complete' && result.info === 'OK') {
            self.markPosition = [result.poiList.pois[0].location.lng, result.poiList.pois[0].location.lat]
            self.addMarker(self.markPosition)
          }
        })
      })
    },
    getAdress (position) {
      var self = this
      AMap.plugin('AMap.Geocoder', function() {
        var geocoder = new AMap.Geocoder({
          city: self.city
        })
        var lnglat = position
        geocoder.getAddress(lnglat, function(status, result) {
          // console.log(status, result)
          if (status === 'complete' && result.info === 'OK') {
            self.ruleForm.address = result.regeocode.formattedAddress.replace('福建省福州市', '')
          }
        })
      })
    },
    // 自定义文件上传
    uploadFile (param) { 
      var fileObj = param.file
      bmf.md5(fileObj, (err, md5) => {
        console.log(err,1)
        var formData = new FormData()
        formData.append('file', fileObj)    
        formData.append('explorerId', -1)
        formData.append('md5', md5)
        formData.append('name', fileObj.name)
        formData.append('parentId', -1)
        this.$store.dispatch('fileFun/UploadFile', formData).then(res => {
          if(res.code == '200'){
            this.logoFileId = res.data.fileId
            this.getPics(this.logoFileId, null)
          }
        })
      })
    },
    // 自定义文件上传
    uploadFile1 (param) { 
      var fileObj = param.file
      bmf.md5(fileObj, (err, md5) => {
        console.log(err,1)
        var formData = new FormData()
        formData.append('file', fileObj)
        formData.append('explorerId', -1)
        formData.append('md5', md5)
        formData.append('name', fileObj.name)
        formData.append('parentId', -1)
        this.$store.dispatch('fileFun/UploadFile', formData).then(res => {
          if(res.code == '200'){
            this.imageFileIds.push(res.data.fileId)
            this.getPics(null, this.imageFileIds)
          }
        })
      })
    },
    submitUpload () {
      this.$refs['cvue-upload'].submit()
    },
    handlePictureCardPreview () {},
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handleResetForm () {
      this.$refs['ruleForm'].resetFields()
    },
    getAreaList (pid) {
      var params = {
        parentId: pid
      }
      this.$store.dispatch('manage/AreaListGet', params).then(res => {
        // console.log(res)
        if (res.code == 200) {
          var data = res.data
          if (res.data[0].level === 1) {
            this.provinceArr = data
          } else {
            this.cityArr = data
          }
        }
      }).catch(err => {
        console.log(err)
      })
    },
    getStoreDetail () {
      var params = {
        id: this.$route.query.id
      }
      this.$store.dispatch('manage/StoreDetailGet', params).then(res => {
        console.log(res)
        if (res.code == 200) {
          var data = res.data
          // console.log(data)
          this.$set(this.ruleForm, 'storeName', data.storeName)
          this.$set(this.ruleForm, 'telephone', data.telephone)
          this.$set(this.ruleForm, 'maxCapacity', data.maxCapacity)
          this.$set(this.ruleForm, 'siteArea', data.siteArea)
          this.$set(this.ruleForm, 'province', data.province)
          this.$set(this.ruleForm, 'city', data.city)
          this.$set(this.ruleForm, 'address', data.address)
          this.$set(this.ruleForm, 'introduce', data.introduce)
          this.logoFileId = data.logoFileId
          this.imageFileIds = data.imageFileIds?data.imageFileIds:[]
          this.shopId = data.id
          this.getPics(data.logoFileId, data.imageFileIds)
          if(data.longitude && data.latitude){
            this.markPosition = [data.longitude, data.latitude]
            this.addMarker(this.markPosition)
          }
        }
      }).catch(err => {
        console.log(err)
      })
    },
    async getPics (logoFileId, imageFileIds) {
      if (logoFileId) {
        var logoFile = await this.getPic(logoFileId)
        this.logoFile = logoFile.data
      }
      if (imageFileIds) {
        var imageUrlArr = []
        for(let i = 0; i < imageFileIds.length; i++){
          var imageItem = await this.getPic(imageFileIds[i])
          imageUrlArr.push(imageItem.data)
        }
        this.imageFiles = imageUrlArr
      }
    },
    getPic (fileId) {
      var paramsData = {
        fileId: fileId
      }
      return this.$store.dispatch('fileFun/GetPublicUrl', paramsData)
    },
    deleteImage (index) {
      this.imageFiles.splice(index, 1)
      this.imageFileIds.splice(index, 1)
    },
    getCity (val) {
      this.getAreaList(val)
    },
    // 关闭弹窗
    closeDialog () {
      this.closeTagTo('/home/shop-manage')
    },
    // 确认
    confirmDialog () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          var params = {
            "id": this.$route.query.action == 'add' ? '' : this.shopId,
            "address": this.ruleForm.address,
            "city": this.ruleForm.city,
            "county": 0,
            "enabled": 1,
            "imageFileIds": this.imageFileIds,
            "longitude": this.markPosition[0],
            "latitude": this.markPosition[1],
            "introduce": this.ruleForm.introduce,
            "logoFileId": this.logoFileId,
            "maxCapacity": this.ruleForm.maxCapacity,
            "siteArea": this.ruleForm.siteArea,
            "province": this.ruleForm.province,
            "storeName": this.ruleForm.storeName,
            "telephone": this.ruleForm.telephone
          }
          // console.log(params)
          this.dialogLoading = true
          var url = this.$route.query.action == 'add' ? 'manage/StoreAdd' : 'manage/StoreEdit'
          this.$store.dispatch(url, params).then(res => {
            // console.log(res)
            if(res.code == '200'){
              this.$message({
                message: res.msg,
                duration: 2000,
                type: 'success'
              })
              // this.$emit('confirmDialog')
              this.closeTagTo('/home/shop-manage')
            } else {
              this.$message({
                message: res.msg,
                duration: 2000,
                type: 'error'
              })
            }
            this.dialogLoading = false
          }).catch(err => {
            this.$message({ message: err.msg, duration: 2000, type: 'error' })
            this.dialogLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
.shop-edit {
  padding: 0px 0 60px !important;
  height: auto !important;
  position: relative;
  .btn-list {
    float: right;
    margin-right: 10px;
    font-size: 12px;
    color: #409EFF;
    cursor: pointer;
  }
  .el-card__header,
  .el-card__body {
    padding: 15px;
  }
  .fix-lh {
    line-height: 32px;
  }
  .el-input.is-disabled .el-input__inner {
    color: #606266;
  }
  .left{
    min-height:500px;
    background:#fff;
  }
  .left-tree{
    width: 100%;
    min-height:600px;
    overflow: auto;
  }
  .left-top{
    width: 100%;
    height: 40px;
    text-align: center;
    line-height: 40px;
    font-size: 16px;
    color: #333;
    background: #e2e2e2;
    font-size: 15px;
  }
  .box-card{
    margin-bottom: 10px;
  }
  .avtar-wrap{
    padding: 10px 30px 30px;
    .avtar-item{
      width: 158px;
      margin: 0 auto 50px;
      p{
        line-height: 26px;
        color: #bbb;
      }
      .avtar-tip{
        color: #555;
      }
    }
  }

  .avatar-uploader {
    .el-upload{
      // display: flex;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 148px;
      height: 148px;
      line-height: 148px;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader-icon:hover{
      border-color: #409EFF;
    }
    .fix-upload .avatar-uploader-icon{
      border: none;
    }
    .list-upload-image{
      // max-width: 800px;
      overflow: hidden;
      li{
        width: 148px;
        height: 148px;
        line-height: 148px;
        display: inline-block;
        margin: 0 5px 5px;
        border: 1px dashed #d9d9d9;
        float: left;
        position: relative;
        .image-item{
          // width: 100%;
          // height: 100%;
          max-width: 100%;
          max-height: 100%;
          vertical-align: middle;
        }
        .icon-close{
          position: absolute;
          right: 0px;
          top: 0px;
          color: red;
          font-size: 18px;
        }
      }
    }
  }
  .edit-footer{
    width: calc(100% - 248px);
    height: 60px;
    line-height: 60px;
    position: fixed;
    background: #fff;
    left: 230px;
    bottom: 0;
    padding-left: 20px;
    box-sizing: border-box;
  }
  #addressMap{
    width: 100%;
    height: 300px;
  }
  .fix-address{
    margin-bottom: 0px !important;
  }
}
</style>
